package com.mobilesalon.contact;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.Contacts;

public class ContactProvider {

	private Context context;

	public ContactProvider(Context context) {
		this.context = context;
	}

	public Contact getContactByEmailAdress(String mailAdress) {
		Uri uri = Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(mailAdress));
		Cursor emailCursor = context.getContentResolver().query(uri,
				new String[] { Email.LOOKUP_KEY }, null, null, null);

		if (emailCursor.moveToNext()) {
			String contactLookupKey = emailCursor.getString(emailCursor
					.getColumnIndex(Email.LOOKUP_KEY));
			return this.getContactDetailsByLookupKey(contactLookupKey);

		}

		return null;
	}

	public Contact getContactDetailsByLookupKey(String lookupKey) {
		Contact contact = new Contact();
		
		Uri contactLookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI,
				lookupKey);
		Cursor cursor = context.getContentResolver().query(contactLookupUri,
				new String[] {Contacts.LOOKUP_KEY, Contacts.DISPLAY_NAME}, null, null, null);
		try {
			cursor.moveToFirst();
			contact.setDisplayName(cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME)));
			contact.setLookupKey(cursor.getString(cursor.getColumnIndex(Contacts.LOOKUP_KEY)));
			
		} finally {
			cursor.close();
		}
		return contact;
	}
}
